package com.ruoyi.thread.entity.init;

import com.ruoyi.thread.entity.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

@Service
@Slf4j
public class DataInitService {
    
    private static final Random random = new Random();
    private static final List<String> CATEGORIES = Arrays.asList(
        "电子产品", "服装", "食品", "家居", "图书", "美妆", "运动户外"
    );
    
    private List<User> users = new ArrayList<>();
    private List<Product> products = new ArrayList<>();
    private List<Order> orders = new ArrayList<>();
    private List<Message> messages = new ArrayList<>();

    public void initData() {
        log.info("开始初始化模拟数据...");
        initUsers();
        initProducts();
        initOrders();
        initMessages();
        log.info("模拟数据初始化完成！用户: {}个, 商品: {}个, 订单: {}个, 消息: {}个", 
                users.size(), products.size(), orders.size(), messages.size());
    }
    
    private void initUsers() {
        for (long i = 1; i <= 50; i++) {
            users.add(new User(
                i,
                "user" + i,
                "user" + i + "@example.com",
                "138" + String.format("%08d", i),
                18 + random.nextInt(50),
                "地址" + i,
                LocalDateTime.now().minusDays(random.nextInt(365)),
                User.UserStatus.ACTIVE
            ));
        }
    }
    
    private void initProducts() {
        for (long i = 1; i <= 100; i++) {
            products.add(new Product(
                i,
                "商品" + i,
                CATEGORIES.get(random.nextInt(CATEGORIES.size())),
                BigDecimal.valueOf(10 + random.nextInt(990)),
                50 + random.nextInt(200),
                "这是商品" + i + "的描述",
                Product.ProductStatus.ON_SALE,
                LocalDateTime.now().minusDays(random.nextInt(100))
            ));
        }
    }
    
    private void initOrders() {
        for (long i = 1; i <= 200; i++) {
            Long userId = 1L + random.nextInt(users.size());
            List<OrderItem> items = new ArrayList<>();
            BigDecimal totalAmount = BigDecimal.ZERO;
            
            // 每个订单1-3个商品
            int itemCount = 1 + random.nextInt(3);
            for (int j = 0; j < itemCount; j++) {
                Product product = products.get(random.nextInt(products.size()));
                Integer quantity = 1 + random.nextInt(3);
                BigDecimal subtotal = product.getPrice().multiply(BigDecimal.valueOf(quantity));
                
                items.add(new OrderItem(
                    product.getId(),
                    product.getName(),
                    quantity,
                    product.getPrice(),
                    subtotal
                ));
                totalAmount = totalAmount.add(subtotal);
            }
            
            orders.add(new Order(
                i,
                userId,
                items,
                totalAmount,
                Order.OrderStatus.values()[random.nextInt(Order.OrderStatus.values().length)],
                "收货地址" + i,
                LocalDateTime.now().minusDays(random.nextInt(30)),
                LocalDateTime.now().minusDays(random.nextInt(30))
            ));
        }
    }
    
    private void initMessages() {
        for (long i = 1; i <= 300; i++) {
            Long userId = 1L + random.nextInt(users.size());
            messages.add(new Message(
                i,
                userId,
                "消息标题" + i,
                "这是消息" + i + "的内容",
                Message.MessageType.values()[random.nextInt(Message.MessageType.values().length)],
                random.nextBoolean(),
                LocalDateTime.now().minusHours(random.nextInt(720))
            ));
        }
    }
    
    // 获取服务方法
    public List<User> getUsers() {
        return new ArrayList<>(users);
    }
    
    public List<Product> getProducts() {
        return new ArrayList<>(products);
    }
    
    public List<Order> getOrders() {
        return new ArrayList<>(orders);
    }
    
    public List<Message> getMessages() {
        return new ArrayList<>(messages);
    }
    
    // 根据ID查找
    public User findUserById(Long id) {
        simulateQueryDelay(100, 200); // 模拟数据库查询延迟
        return users.stream()
                .filter(user -> user.getId().equals(id))
                .findFirst()
                .orElse(null);
    }
    
    public Product findProductById(Long id) {
        simulateQueryDelay(80, 150);
        return products.stream()
                .filter(product -> product.getId().equals(id))
                .findFirst()
                .orElse(null);
    }
    
    public List<Order> findOrdersByUserId(Long userId) {
        simulateQueryDelay(150, 300);
        return orders.stream()
                .filter(order -> order.getUserId().equals(userId))
                .collect(Collectors.toList());
    }
    
    public List<Message> findMessagesByUserId(Long userId) {
        simulateQueryDelay(120, 250);
        return messages.stream()
                .filter(message -> message.getUserId().equals(userId) && !message.getRead())
                .collect(Collectors.toList());
    }
    
    private void simulateQueryDelay(int minMs, int maxMs) {
        try {
            Thread.sleep(minMs + random.nextInt(maxMs - minMs));
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}